package qeb.handheldmedical.helper;

import android.content.Context;
import android.content.pm.PackageManager.NameNotFoundException;
import android.text.TextUtils;
import android.util.Log;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import qeb.handheldmedical.R;
import qeb.handheldmedical.model.Phone;
import qeb.handheldmedical.model.User;

public class WSHelper {

    // txtloadmes.setText(read_file.GetIpadd().toString()+read_file.GetWebservicename().toString());
    // private static String WSUrl =
    // "http://61.153.43.244:8989/WebService/MEMRWebService.asmx";
    // private static String WSUrl =
    // "http://61.153.43.244:8989/webservice/memrwebservice.asmx";
    // "http://192.168.0.149/Webservice.asmx";
    private static String WSUrl = "http://192.168.10.248:9002/WebService/MEMRWebService.asmx";
    private static String namespace = "http://qebsoft.com/";

    private static String TAG = "WSHelper";
    // http://61.153.43.244:8989/apk/ver.txt
    // public static final String UPDATE_SERVER =
    // "http://61.153.43.244:8989/apk/";
    public static final String UPDATE_SERVER = "http://192.168.10.248/PdaForAndroid/";
    public static final String UPDATE_APKNAME = "hm.apk";
    public static final String UPDATE_VERJSON = "ver.txt";
    public static final String UPDATE_SAVENAME = "hm_update.apk";

    /*************************************
     * 获取web services内容
     *
//     * @param url
     * @param params
     * @return
     *************************************/
    public static String GetResponse(String method,
                                     List<BasicNameValuePair> params) {
        String reslut = "";
        try {
            String url = WSUrl;
            SoapObject request = new SoapObject(namespace, method);
            for (int i = 0, len = params.size(); i < len; i++) {
                request.addProperty(params.get(i).getName(), params.get(i)
                        .getValue());
            }
            SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
                    SoapEnvelope.VER11);
            envelope.dotNet = true;
            envelope.setOutputSoapObject(request);
            // 设置30秒超时s
            HttpTransport transport = new HttpTransport(url, 30000);
            transport.call(namespace + method, envelope);
            //SoapPrimitive result1 = (SoapPrimitive) envelope.getResponse();
            SoapObject response = (SoapObject) envelope.bodyIn;
            reslut = response.getProperty(0).toString();

            //reslut = response.toString();

        } catch (Exception e) {
            Log.v("读取数据出现异常：", e.toString());
            return null;
        }
        return reslut;
    }

    // 登录
    public static User Login(String gh, String password) {
        User usr = new User();
        try {
            final List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
            params.add(new BasicNameValuePair("gh", String.valueOf(gh)));
            params.add(new BasicNameValuePair("password", String
                    .valueOf(password)));
            String reslutString = GetResponse("Login", params);
            if (reslutString != null) {
                JSONObject jobj = new JSONObject(reslutString);
                if (jobj != null) {
                    usr.getValue(jobj);
                }
            }
        } catch (Exception e) {
            return null;
        }
        return usr;
    }

    // 调用webservice 医嘱函数
    public static String exeAdvice(String funName,
                                   Map<String, String> map) {
        final List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
        for (String key : map.keySet()) {
            params.add(new BasicNameValuePair(key, map.get(key)));
        }
        return GetResponse(funName, params);
    }


    // 手机客服端信息
    public static Phone GetPhoneInfo(String deviceid) {
        Phone phone = new Phone();
        try {
            final List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
            params.add(new BasicNameValuePair("deviceid", deviceid));
            String reslutString = GetResponse("GetPhoneInfo", params);
            if (reslutString != null) {
                JSONObject jobj = new JSONObject(reslutString);
                if (jobj != null) {
                    phone.getValue(jobj);
                }
            }
        } catch (Exception e) {
        }
        return phone;
    }

    // 手机客服端列表
    public static JSONArray GetPhoneList() {
        JSONArray ips = null;
        final List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
        String reslutString = GetResponse("GetPhoneList", params);
        if (reslutString != null) {
            try {
                ips = new JSONArray(reslutString);
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                // e.printStackTrace();
            }
        }
        return ips;
    }

    // 手机信息插入
    public static Phone InsertPhoneInfo(String phoneInfo) {
        Phone phone = new Phone();
        try {
            final List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
            params.add(new BasicNameValuePair("phoneInfo", phoneInfo));
            String reslutString = GetResponse("InsertPhoneInfo", params);
            if (reslutString != null) {
                JSONObject jobj = new JSONObject(reslutString);
                if (jobj != null) {
                    phone.getValue(jobj);
                }
            }
        } catch (Exception e) {
        }
        return phone;
    }

    // 手机信息插入
    public static Phone UpdatePhoneInfo(String phoneInfo) {
        Phone phone = new Phone();
        try {
            final List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
            params.add(new BasicNameValuePair("phoneInfo", phoneInfo));
            String reslutString = GetResponse("UpdatePhoneInfo", params);
            if (reslutString != null) {
                JSONObject jobj = new JSONObject(reslutString);
                if (jobj != null) {
                    phone.getValue(jobj);
                }
            }
        } catch (Exception e) {
        }
        return phone;
    }

    // 获取病人列表
    public static JSONArray GetPatientList(String bqid, String stateid,
                                           String keyword, String ylz) {
        JSONArray ips = null;
        final List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
        params.add(new BasicNameValuePair("bqid", bqid));
        // params.add(new BasicNameValuePair("userid", String.valueOf(userid)));
        params.add(new BasicNameValuePair("stateid", stateid));
        params.add(new BasicNameValuePair("keyword", keyword));
        params.add(new BasicNameValuePair("ylz", ylz));
        String reslutString = GetResponse("GetPatientList", params);
        if (reslutString != null) {
            try {
                ips = new JSONArray(reslutString);
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                // e.printStackTrace();
            }
        }
        return ips;
    }

    // 获取病人血糖
    public static JSONArray GetXtList(String zyxh) {
        JSONArray ips = null;
        final List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
        params.add(new BasicNameValuePair("zyxh", zyxh));
        String reslutString = GetResponse("GetXtjlList", params);
        if (reslutString != null) {
            try {
                ips = new JSONArray(reslutString);
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                // e.printStackTrace();
            }
        }
        return ips;
    }

    // 获取病人检查报告列表
    public static JSONArray GetPacsList(String rysj, String cysj, String bah) {
        JSONArray ips = null;
        final List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
        params.add(new BasicNameValuePair("rysj", rysj));
        params.add(new BasicNameValuePair("cysj", cysj));
        params.add(new BasicNameValuePair("bah", String.valueOf(bah)));
        String reslutString = GetResponse("GetJcList", params);
        if (reslutString != null) {
            try {
                ips = new JSONArray(reslutString);
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                // e.printStackTrace();
            }
        }
        return ips;
    }

    // 获取病人检验报告列表
    public static JSONArray GetLisList(String jySjStart, String jySjEnd,
                                       String bah, String hiszyxh) {
        JSONArray ips = null;
        final List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
        params.add(new BasicNameValuePair("jySjStart", jySjStart));
        params.add(new BasicNameValuePair("jySjEnd", jySjEnd));
        params.add(new BasicNameValuePair("bah", bah));
        params.add(new BasicNameValuePair("hiszyxh", hiszyxh));
        String reslutString = GetResponse("GetJyList", params);
        if (reslutString != null) {
            try {
                ips = new JSONArray(reslutString);
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                // e.printStackTrace();
            }
        }
        return ips;
    }

    // 获取病人检验报告列表
    public static JSONArray GetLisResultList(String zxh) {
        JSONArray ips = null;
        final List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
        params.add(new BasicNameValuePair("zxh", zxh));
        String reslutString = GetResponse("GetJyjgList", params);
        if (reslutString != null) {
            try {
                ips = new JSONArray(reslutString);
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                // e.printStackTrace();
            }
        }
        return ips;
    }

    // 获取病人体温
    public static JSONArray GetTemperature(String zyxh) {
        JSONArray ips = null;
        final List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
        params.add(new BasicNameValuePair("zyxh", zyxh));
        String reslutString = GetResponse("GetTwjlList", params);
        if (reslutString != null) {
            try {
                ips = new JSONArray(reslutString);
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                // e.printStackTrace();
            }
        }
        return ips;
    }

    // 获取病人手术报告列表
    public static JSONArray GetSsListByZyxh(String zyxh) {
        JSONArray ips = null;
        final List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
        params.add(new BasicNameValuePair("zyxh", zyxh));
        params.add(new BasicNameValuePair("SqSsj", ""));
        params.add(new BasicNameValuePair("sqsjend", ""));
        String reslutString = GetResponse("GetSsListByZyxh", params);
        if (reslutString != null) {
            try {
                ips = new JSONArray(reslutString);
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                // e.printStackTrace();
            }
        }
        return ips;
    }

    // 获取病人会诊详细信息
    public static JSONArray GetHzDetailByEventID(String autoID) {
        JSONArray ipss = new JSONArray();
        final List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
        params.add(new BasicNameValuePair("autoid", autoID));
        String reslutString = GetResponse("GetHzDetail", params);
        if (reslutString != null) {
            try {
                ipss = new JSONArray(reslutString);
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return ipss;
    }

    // 获取会诊请求列表
    public static JSONArray GetHzdQQ(String zyxh, String qqdid, String qqkID,
                                     String strStartDate, String strEndDate) {
        JSONArray ips = null;
        final List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
        params.add(new BasicNameValuePair("zyxh", zyxh));
        params.add(new BasicNameValuePair("qqdid", qqdid));
        params.add(new BasicNameValuePair("qqkID", qqkID));
        params.add(new BasicNameValuePair("strStartDate", strStartDate));
        params.add(new BasicNameValuePair("strEndDate", strEndDate));
        String reslutString = GetResponse("GetHzdQQ", params);
        if (reslutString != null) {
            try {
                ips = new JSONArray(reslutString);
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return ips;
    }

    // 获取会诊回复列表
    public static JSONArray GetHzdDf(String zyxh, String dfdid, String kname,
                                     String strStartDate, String strEndDate) {
        JSONArray ips = null;
        final List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
        params.add(new BasicNameValuePair("zyxh", zyxh));
        params.add(new BasicNameValuePair("dfdid", dfdid));
        params.add(new BasicNameValuePair("kname", kname));
        params.add(new BasicNameValuePair("strStartDate", strStartDate));
        params.add(new BasicNameValuePair("strEndDate", strEndDate));
        String reslutString = GetResponse("GetHzdHF", params);
        if (reslutString != null) {
            try {
                ips = new JSONArray(reslutString);
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return ips;
    }

    // 获取手术通知单列表
    public static JSONArray GetSstzd(String Sszt, String Sslb, String Ylz,
                                     String SqSsj, String SqsjEnd, String bqid) {
        JSONArray ips = null;
        final List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
        params.add(new BasicNameValuePair("Sszt", Sszt));
        params.add(new BasicNameValuePair("Sslb", Sslb));
        params.add(new BasicNameValuePair("Ylz", Ylz));
        params.add(new BasicNameValuePair("SqSsj", SqSsj));
        params.add(new BasicNameValuePair("SqsjEnd", SqsjEnd));
        params.add(new BasicNameValuePair("bqid", bqid));
        String reslutString = GetResponse("GetSstzd", params);
        if (reslutString != null) {
            try {
                ips = new JSONArray(reslutString);
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return ips;
    }

    // 获取当前版本号ID
    public static int getVerCode(Context context) {
        int verCode = -1;
        try {
            verCode = context.getPackageManager().getPackageInfo(
                    "qeb.handheldmedical", 0).versionCode;
        } catch (NameNotFoundException e) {
            Log.e(TAG, e.getMessage());
        }
        return verCode;
    }

    public static String getVerName(Context context) {
        String verName = "";
        try {
            verName = context.getPackageManager().getPackageInfo(
                    "qeb.handheldmedical", 0).versionName;
        } catch (NameNotFoundException e) {
            Log.e(TAG, e.getMessage());
        }
        return verName;

    }

    public static String getAppName(Context context) {
        String verName = context.getResources().getText(R.string.app_name)
                .toString();
        return verName;
    }

    public static String getContentWebService(String url) {
        final List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
        params.add(new BasicNameValuePair("type", "1"));
        String reslutString = GetResponse("GetVersionMessage", params);
        return reslutString;

    }

    public static String getContent(String url) {
        StringBuilder sb = new StringBuilder();

        HttpClient client = new DefaultHttpClient();
        HttpParams httpParams = client.getParams();
        // client
        HttpConnectionParams.setConnectionTimeout(httpParams, 3000);
        HttpConnectionParams.setSoTimeout(httpParams, 5000);
        HttpResponse response;
        try {
            response = client.execute(new HttpGet(url));
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(entity.getContent(), "UTF-8"),
                        8192);

                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
                reader.close();
            }
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return sb.toString();

    }

    // 获取病人详细信息
    public static JSONArray GetPatientInfo(String zyxh) {
        JSONArray ipss = null;
        final List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
        params.add(new BasicNameValuePair("zyxh", zyxh));
        String reslutString = GetResponse("GetPatientInfo", params);
        if (!TextUtils.isEmpty(reslutString)) {
            try {
                ipss = new JSONArray(reslutString);
            } catch (Exception e) {
                return ipss;
            }
        }
        return ipss;
    }

    // 调用webservice函数
    public static JSONArray getWebserviceFun(String funName,
                                             Map<String, String> map) {
        JSONArray jsonArray = null;
        final List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
        for (String key : map.keySet()) {
            params.add(new BasicNameValuePair(key, map.get(key)));
        }

        String reslutString = GetResponse(funName, params);
        if (!TextUtils.isEmpty(reslutString) && !"[]".equals(reslutString)) {
            try {
                jsonArray = new JSONArray(reslutString);
            } catch (Exception e) {
                return null;
            }
        }
        return jsonArray;
    }

    public static JSONArray getAdviceList(String funName,
                                          Map<String, String> map){
            JSONArray jsonArray = null;
            final List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
            for (String key : map.keySet()) {
                params.add(new BasicNameValuePair(key, map.get(key)));
            }

            String reslutString = GetResponse(funName, params);
//            LogListActivity.logList.add("获取医嘱原始响应数据: "+reslutString);
            if (!TextUtils.isEmpty(reslutString)) {
                try {
                    jsonArray = new JSONArray(reslutString);
                } catch (Exception e) {
                    return null;
                }
            }
        return jsonArray;

    }

    // 调用webservice函数
    public static JSONObject getWebserviceJsonObject(String funName,
                                                     Map<String, String> map) {
        JSONObject jsonArray = null;
        final List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
        for (String key : map.keySet()) {
            params.add(new BasicNameValuePair(key, map.get(key)));
        }

        String reslutString = GetResponse(funName, params);
        if (!TextUtils.isEmpty(reslutString)) {
            try {
                jsonArray = new JSONObject(reslutString);
            } catch (Exception e) {
                return null;
            }
        }
        return jsonArray;
    }

    // 调用webservice函数
    public static String getWebserviceString(String funName,
                                             Map<String, String> map) {
        final List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
        for (String key : map.keySet()) {
            params.add(new BasicNameValuePair(key, map.get(key)));
        }

        String reslutString = GetResponse(funName, params);

        return reslutString;
    }
}
